using System;
using System.Collections.Generic;
using Cysharp.Threading.Tasks;
using TEngine;
using YIUIFramework;
using YooAsset;
using Object = UnityEngine.Object;

namespace GameLogic
{
    public class YiUIRegister: Singleton<YiUIRegister>
    {
        private Dictionary<int,AssetHandle> m_AllHandle = new Dictionary<int,AssetHandle>();

        public async UniTask Register()
        {
            UIBindHelper.InternalGameGetUIBindVoFunc = YIUICodeGenerated.UIBindProvider.Get;
            YIUILoadDI.LoadAssetFunc = LoadAsset;
            YIUILoadDI.LoadAssetAsyncFunc = LoadAssetAsync;
            YIUILoadDI.ReleaseAction = ReleaseAction;
            
            SingletonMgr.Initialize();
            
            await MgrCenter.Inst.Register(CountDownMgr.Inst);
            await MgrCenter.Inst.Register(RedDotMgr.Inst);
            await MgrCenter.Inst.Register(PanelMgr.Inst);
        }

        private void ReleaseAction(int hashCode)
        {
            if (m_AllHandle.TryGetValue(hashCode, out var handle))
            {
                handle.Release();
                m_AllHandle.Remove(hashCode);
            }
            else
            {
                Log.Error("释放了一个未知Code");
            }
        }

        private async UniTask<(Object, int)> LoadAssetAsync(string pkgName, string resName, Type resType)
        {
            var handle = GameModule.Resource.LoadAssetAsyncHandle(resName, resType);
            await handle.ToUniTask();
            return LoadAssetHandle(handle);
        }

        private (Object, int) LoadAsset(string pkgName, string resName, Type resType)
        {
            var handle = GameModule.Resource.LoadAssetSyncHandle(resName, resType);
            return LoadAssetHandle(handle);
        }

        private (Object, int) LoadAssetHandle(AssetHandle handle)
        {
            if (handle.AssetObject != null)
            {
                var hashCode = handle.GetHashCode();
                m_AllHandle.Add(hashCode, handle);
                return (handle.AssetObject, hashCode);
            }
            else
            {
                handle.Release();
                return (null, 0);
            }
        }
    }
}